package com.atguigu.guliguli.product.service.impl;

import com.atguigu.guliguli.common.utils.PageUtils;
import com.atguigu.guliguli.common.utils.Query;
import com.atguigu.guliguli.product.entity.BrandEntity;
import com.atguigu.guliguli.product.mapper.BrandMapper;
import com.atguigu.guliguli.product.service.BrandService;
import com.atguigu.guliguli.product.service.CategoryBrandRelationService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @author: 叶子
 * @date: 2021/11/27 15:26
 **/
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, BrandEntity>implements BrandService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
//        获取key
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(key)){
            queryWrapper.eq("brand_id",key).or().like("name",key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void updateDetail(BrandEntity brand) {
//    保证冗余字段的数据一致
        this.updateById(brand);
        if (StringUtils.isNotEmpty(brand.getName())){
//            同步更新其他关联表中的数据
            categoryBrandRelationService.updateBrand(brand.getBrandId(),brand.getName());
//      todo 更新其他关联
        }
    }
}